<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar @queryTable="Refresh"></right-toolbar>
    </el-row>

    <vxe-table v-loading="tableData.loading" style="height: 100%;flex-grow: 1;"
               border="full"
               ref="tableRef"
               :column-config="{resizable: true}"
               :data="tableData.list">
      <vxe-column field="name" title="名称"></vxe-column>
      <vxe-column field="number" title="序列号"></vxe-column>

      <vxe-column title="类型">
        <template #default="{row}">
          {{getHardwareTypeShow(row.hardwareType)}}
        </template>
      </vxe-column>

      <vxe-column title="是否自动启动">
        <template #default="scope">
          {{scope.row.autoStartFlag == 1 ? '是':'否'}}
        </template>
      </vxe-column>
      <vxe-column title="连接状态">
        <template #default="scope">
          <span style="color: rgb(103, 194, 58);" v-if="scope.row.status">已连接</span>
          <span style="color: rgb(245, 108, 108);" v-else>已断开</span>
        </template>
      </vxe-column>
      <vxe-column title="操作">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              link
              @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
              size="small"
              type="primary"
              link
              @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button v-if="scope.row.status == 1"
                     size="small"
                     type="primary"
                     link
                     @click="handleShutdown(scope.row)"
          >关闭</el-button>

          <el-button
              size="small"
              type="primary"
              link
              @click="handleViewMessage(scope.row)"
          >查看RFID</el-button>
        </template>
      </vxe-column>

    </vxe-table>

    <edit ref="editDialog" @sub="getList"></edit>
    <chat ref="chatDialog" @sub="getList"></chat>

    <inventory-dialog ref="inventoryDialog"></inventory-dialog>
  </div>
</template>

<script setup>

import api from "./api.js";
import Edit from './edit'
import Chat from "@/views/setup/hardware/chat.vue";
import InventoryDialog from "@/views/setup/hardware/RFIDDialog.vue";

const hardwareTypeList = [{
  label: 'RFID打印机',
  value: '1'
}, {
  label: 'RFID天线',
  value: '2'
}, {
  label: 'RFID通道门',
  value: '3'
}];

const { proxy } = getCurrentInstance();
const editDialog = ref();
const chatDialog = ref();
const inventoryDialog = ref();

// 遮罩层
const loading = ref(false);
const tableData = reactive({
  loading: false,
  list: [], // 表格列表数据
  paging: {
    total: 0, // 总条数
    pageNum: 1,
    pageSize: 10,
  }
});

const initQueryParams = {
  pageNum: 1,
  pageSize: 10,
  number: null,
  name: null,
  categoryId: null,
  rfid: null,
  brand: null,
  model: null,
  buyWay: null,
  buyTime: null,
  buyPrice: null,
  adminId: null
}

const queryParams = reactive({...initQueryParams})

/** 查询资产清单表列表 */
async function getList() {

  loading.value = true;
  const {pageNum, pageSize} = tableData.paging;
  const query = {...queryParams};
  const pageReq = {page: pageNum - 1, size: pageSize};
  api.list(query, pageReq).then(response => {

    tableData.list = response;
    tableData.loading = false;
 
  }).catch(error => {
    
    tableData.loading = false;

    console.log(error);
  });
}
function Refresh() {
  proxy.$message.success("刷新成功");
}

/** 新增按钮操作 */
function handleAdd() {
  editDialog.value.open();
}

function getHardwareTypeShow(typeId) {
  let one = hardwareTypeList.find(item => parseInt(item.value) === typeId);
  if (!one) {
    return null;
  }
  return one.label;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  editDialog.value.open(row);
}


function handleViewMessage(row) {
  inventoryDialog.value.open(row);
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || this.ids;
  proxy.$modal.confirm('是否确认删除资产清单表编号为"' + ids + '"的数据项？').then(function() {
    return api.del(ids);  
  }).then(() => {
    getList(); 
    proxy.$modal.msgSuccess("删除成功");  
  }).catch(() => {
    proxy.$modal.msgError("删除失败");  
  });
}



function handleStart(row) {
  api.start(row.id).then(()=>{
    this.getList();
  });
}

function handleShutdown(row) {
  api.shutdown(row.id).then(()=>{
    this.getList();
  });
}

/** 导出按钮操作 */
function handleExport() {
  const queryParams = this.queryParams;
  this.$modal.confirm('是否确认导出所有资产清单表数据项？').then(() => {
    this.exportLoading = true;
    return exportAssetItem(queryParams);
  }).then(response => {
    this.$download.download(response);
    this.exportLoading = false;
  }).catch(() => {});
}

// 向服务器请求信息

let socket = null;

function setDeviceStatus(uuid, status) {
  const d = tableData.list.find(item => item.number === uuid);
  if (!d) {
    console.warn(`序列号为${uuid}的设备不存在`);
    return;
  }
  d.status = status;
}

function createWebsocket() {

  const location = window.location;
  const hostname = location.hostname;

  socket = new WebSocket(`ws://${hostname}:8085/device`);

  // Set up event listeners
  socket.onopen = (event) => {
    console.log('WebSocket connection opened.');
  };

  socket.onmessage = (event) => {
    const data = event.data;
    const message = JSON.parse(data);
    setDeviceStatus(message.uuid, message.status);
  };

  socket.onerror = (error) => {
    console.error('WebSocket Error:', error);
  };

  socket.onclose = (event) => {
    console.log('WebSocket connection closed.');
  };

  return socket;
}

function closeWebsocket() {
  if (socket) {
    socket.close();
  }

}

// 页面打开后获取列表数据
onMounted( async () => {
  await getList();
  createWebsocket();
});

</script>
